/**
 * LoRA列表选择器模型按钮扩展
 * 为LoraListSelectorModelOnly节点添加LoRA管理器按钮
 */

import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";

// 注册扩展
app.registerExtension({
    name: "ComfyUI-xhh.lora_list_selector_model_only_button",
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        // 只处理XHH_LoraListSelectorModelOnly节点
        if (nodeData.name !== "XHH_LoraListSelectorModelOnly") {
            return;
        }

        console.log("🎯 注册LoraListSelectorModelOnly节点扩展");

        // 重写onNodeCreated方法
        const originalOnNodeCreated = nodeType.prototype.onNodeCreated;
        nodeType.prototype.onNodeCreated = function() {
            if (originalOnNodeCreated) {
                originalOnNodeCreated.apply(this, arguments);
            }

            console.log("🎯 创建LoraListSelectorModelOnly节点");

            // 添加LoRA管理器按钮
            this.addWidget("button", "🎯 LoRA管理器", null, () => {
                console.log("🎯 点击LoRA管理器按钮");
                this.openLoraManager();
            });

            // 存储节点引用
            this.loraManagerNode = this;
        };

        // 添加打开LoRA管理器的方法
        nodeType.prototype.openLoraManager = function() {
            try {
                console.log("🎯 打开LoRA管理器");

                // 获取include和exclude参数
                const includeWidget = this.widgets.find(w => w.name === "include");
                const excludeWidget = this.widgets.find(w => w.name === "exclude");
                
                const includeValue = includeWidget ? includeWidget.value || "" : "";
                const excludeValue = excludeWidget ? excludeWidget.value || "" : "";

                console.log("🎯 include参数:", includeValue);
                console.log("🎯 exclude参数:", excludeValue);

                // 构建URL参数
                const params = new URLSearchParams();
                if (includeValue.trim()) {
                    params.append('include', includeValue.trim());
                }
                if (excludeValue.trim()) {
                    params.append('exclude', excludeValue.trim());
                }

                const url = `/xhh/lora-manager?${params.toString()}`;
                console.log("🎯 打开URL:", url);

                // 创建模态框
                const modal = document.createElement('div');
                modal.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.8);
                    z-index: 10000;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                `;

                const iframe = document.createElement('iframe');
                iframe.src = url;
                iframe.style.cssText = `
                    width: 95vw;
                    height: 95vh;
                    border: none;
                    border-radius: 8px;
                    background: white;
                `;

                const closeBtn = document.createElement('button');
                closeBtn.innerHTML = '×';
                closeBtn.style.cssText = `
                    position: absolute;
                    top: 10px;
                    right: 10px;
                    background: #ff4444;
                    color: white;
                    border: none;
                    border-radius: 50%;
                    width: 30px;
                    height: 30px;
                    cursor: pointer;
                    font-size: 18px;
                    z-index: 10001;
                `;

                closeBtn.onclick = () => {
                    document.body.removeChild(modal);
                };

                modal.appendChild(iframe);
                modal.appendChild(closeBtn);
                document.body.appendChild(modal);

                // 监听来自iframe的消息
                const messageHandler = (event) => {
                    if (event.data && event.data.type === 'use_lora') {
                        console.log("🎯 收到use_lora消息:", event.data);
                        
                        // 更新selected_lora输入
                        const selectedLoraWidget = this.widgets.find(w => w.name === "selected_lora");
                        if (selectedLoraWidget) {
                            selectedLoraWidget.value = event.data.lora_path;
                            selectedLoraWidget.callback(selectedLoraWidget.value);
                            
                            // 更新输入框显示
                            const inputEl = this.inputs.find(input => input.name === "selected_lora");
                            if (inputEl) {
                                const inputElement = inputEl.parentElement.querySelector('input');
                                if (inputElement) {
                                    inputElement.value = event.data.lora_path;
                                    inputElement.dispatchEvent(new Event('input', { bubbles: true }));
                                    inputElement.dispatchEvent(new Event('change', { bubbles: true }));
                                }
                            }
                        }

                        // 关闭模态框
                        document.body.removeChild(modal);
                        window.removeEventListener('message', messageHandler);
                    }
                };

                window.addEventListener('message', messageHandler);

                console.log("✅ LoRA管理器打开成功");

            } catch (error) {
                console.error("❌ 打开LoRA管理器失败:", error);
                alert("打开LoRA管理器失败: " + error.message);
            }
        };
    }
});
